<?php
require dirname(dirname(__FILE__)).'/abstract.php';
class AutoEmail extends Mage_Shell_Abstract {

    public function run(){
        $this->autoCorrent();
    }
    public function autoCorrent(){
       	//到数据库里取数据
		$read = Mage::getSingleton('core/resource')->getConnection('core_read');
        $sql = " SELECT entity_id,increment_id,store_id,created_at,customer_email,customer_firstname
				FROM sales_flat_order
				WHERE `status`='payment_fail' 
				AND created_at > DATE_SUB(UTC_TIMESTAMP(),INTERVAL 6 HOUR)";
        $result = $read->fetchAll($sql);
		
        foreach ($result as  $value){
            
			//根据视图取邮件模板
			if($value['store_id']==1){
				$code = 'payment_fail_en';
			}else{
				$code = 'payment_fail_ru';
			}
			//发邮件
			if($value['customer_email']){
				//系统发件人
				$sender=Mage::getStoreConfig('sales_email/order/identity', $value['store_id']);
				//邮件模板对象
				$mailTemplate  = Mage::getModel('core/email_template')->loadByCode($code);
				//邮件模板id
				$data=$mailTemplate->getData();
				$template_id = $data['template_id'];
				//传入变量发邮件
				$mailTemplate->setDesignConfig(array('area'=>'frontend', 'store'=>$value['store_id']))  
					->sendTransactional(
					$template_id,  
					$sender,  
					$value['customer_email'], 
					$value['customer_firstname'],
					array(
						'customer_firstname'=>$value['customer_firstname'],
						'created_at'        =>$value['created_at'],
						'increment_id'      =>$value['increment_id'],
					)
				);
			}
		}
		

    }
	
}

/*自动运行*/
		$test = new AutoEmail();
		$test->run();